{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "http://projectsedu.com\n",
      "None\n",
      "2\n",
      "3\n"
     ]
    }
   ],
   "source": [
    "## 生成器基本用法\n",
    "\n",
    "def gen_func():\n",
    "    ## 1. 可以产出值\n",
    "    ## 2. 可以接收值（调用方传递进来的值）\n",
    "    html = yield \"http://projectsedu.com\"\n",
    "    print(html)\n",
    "\n",
    "    yield 2\n",
    "    yield 3\n",
    "    return \"bobby\"\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    gen = gen_func()\n",
    "    print(next(gen))\n",
    "    print(next(gen))\n",
    "    print(next(gen))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "http://projectsedu.com\n",
      "2\n"
     ]
    }
   ],
   "source": [
    "## 使用send传递值到生成器内部\n",
    "\n",
    "def gen_func():\n",
    "    html = yield \"http://projectsedu.com\"\n",
    "    yield 2\n",
    "    print(html)\n",
    "\n",
    "    return \"bobby2\"\n",
    "\n",
    "## 启动生成器的方法有2种，next、send\n",
    "if __name__ == \"__main__\":\n",
    "    gen = gen_func()\n",
    "    ## 在调用send发送非None值之前，必须启动一次生成器\n",
    "    ## 方式1：\n",
    "    ## gen.send(None)\n",
    "    ## 方式2：\n",
    "    ## next(gen)\n",
    "    url = gen.send(None)\n",
    "    # next(gen)\n",
    "    print(url)\n",
    "\n",
    "    ## download url\n",
    "    html = \"bobby1\"\n",
    "    ## send 方法可以传递值进入生成器内部，同时还可以重启生成器执行到下一个yield位置\n",
    "    print(gen.send(html))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "## throw 使用\n",
    "\n",
    "def gen_func():\n",
    "    try:\n",
    "        yield \"http://projectsedu.com\"\n",
    "    except Exception as e:\n",
    "        pass\n",
    "    yield 2\n",
    "    yield 3\n",
    "    return \"bobby\"\n",
    "\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    gen = gen_func()\n",
    "    print(next(gen))\n",
    "    ## 向生成器中抛出异常\n",
    "    gen.throw(Exception, \"download error\")\n",
    "    print(next(gen))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
